#pragma once

#include<iostream>

#include<cerrno>
#include<cstring>

#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>

#include "log.hpp"
class Sock
{
private:
    const static int gbacklog = 20;
public:
    Sock()
    {}

    // 创建套接字
    int Socket()
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock < 0)
        {
            logMessage(FATAL, "create sock erron, %d: %s", errno, strerror(errno));
            exit(1);
        }
        logMessage(NORMAL, "create sock success, listensock: %d", sock);

        return sock;
    }

    // 绑定
    void Bind(int sock, std::string ip, uint16_t port)
    {
        // API
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        // local.sin_addr.s_addr = inet_aton(ip.c_str());
        inet_pton(AF_INET, ip.c_str(), &local.sin_addr);
        local.sin_port = htons(port);

        if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "Bind erron, %d: %s", errno, strerror(errno));
            exit(2);
        }
    }

    // 监听
    void Listen(int sock)
    {
        if(listen(sock, gbacklog) < 0)
        {
            logMessage(FATAL, "listen error, %d: %s", errno, strerror(errno));
            exit(3);
        }
         logMessage(NORMAL, "init server success");
    }

    // 一般: 
    // const std::string &: 输入型参数
    // std::string *: 输出型参数
    // std::string &: 输入输出型参数
    
    // 进行accept(会收到对方的ip+port)
    int Accept(int listensock, std::string* ip, uint16_t* port)
    {
        struct sockaddr_in src;
        socklen_t len = sizeof(src);
        int servicesock = accept(listensock, (struct sockaddr *)&src, &len);
        if (servicesock < 0)
        {
            logMessage(ERROR, "accept error, %d:%s", errno, strerror(errno));
            return -1;
        }
        if(port) *port = ntohs(src.sin_port);
        if(ip) *ip = inet_ntoa(src.sin_addr);
        return servicesock; 
    }

    // 客户端 建立连接
    bool Connect(int sock, const std::string& serverIp, const uint16_t&  serverPort)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(serverPort);
        server.sin_addr.s_addr = inet_addr(serverIp.c_str());

        if(connect(sock, (struct sockaddr*)&server, sizeof(server)) == 0) return true;
        else return false;
    }
};